<?php
    class Lotacao extends BaseModel
    {
        protected $lotacaoid;
        protected $orgaoid;
        protected $nome;
        protected $nucleogestorid;
        protected $rua;
        protected $numero;
        protected $complemento;
        protected $bairro;
        protected $cep;
        protected $fantasia;
        protected $telefone1;
        protected $telefone2;

        const tablename = "lotacoes";
        const tablekey = "lotacaoid";
        const tablesequence = "lotacoes_lotacaoid_seq";

        /**
         * 
         * @return NucleoGestor
         */
        public function getNucleoGestor()
        {
        	$nucleo = new NucleoGestor($this->nucleogestorid);
        	return $nucleo;
        }
        
        public function salvar()
        {
            $this->telefone1 = TUtils::FoneToNum( $this->telefone1 );
            $this->telefone2 = TUtils::FoneToNum( $this->telefone2 );
            $this->cep = TUtils::CepToNum( $this->cep );
            
            parent::salvar();
        }
        
        public function getEndereco()
        {
            $endereco  = '';
            $endereco .= $this->rua . $this->numero . $this->complemento;
            if ( $this->bairro ){
                $endereco .= ' - Bairro: ' . $this->bairro;
            }
            if ( $this->cep ){
                $endereco .= ' - CEP: ' . $this->cep;
            }
            return $endereco;
        }
        
        public function verificarDependencias( $ids )
        {
            $idsSql = '';
            if (is_array ($ids)){
                foreach ($ids as $id){
                    $idsSql .= ', ' . $id;
                }
                $idsSql = substr( $idsSql, 1 );
            }
            elseif (is_numeric ( $ids)){
                $idsSql = $ids;
            }
            else {
                throw new Exception( 'ID inválido.' );
            }
            
            $vaga = new Vaga();
            $result = $vaga->listar( array('precondicao' => $this->getTableKey() . ' IN (' . $idsSql . ')' ) );
            
            if (pg_num_rows ($result) > 0){
                if (is_array ($ids)){
                    throw new Exception( TMensagens::getChavesEstrangeiras() );
                }
                else {
                    throw new Exception( TMensagens::getChaveEstrangeira() );
                }
            }
        }
        
        public function excluir()
        {
            if ( $this->getTableKeyValue() ){
                $this->verificarDependencias ($this->getTableKeyValue());
                parent::excluir();
            }            
        }
        
        public function excluirGrupo ($ids)
        {
            $this->verificarDependencias($ids);
            parent::excluirGrupo ($ids);
        }
    }
?>